/*添加帖子*/
/*获取字数改变*/var imgList=[];
$('#ecchangeMessage,#ecchangeMessage1').keyup(function(){
  var curLen=800-$(this).val().length;
  $('.textCount').html(curLen);
  if(curLen<=0){
    curLen==0;
    $('#ceng').modal('open');
    $('#info-text').html('字数已经超出限制！');
    $('.textCount').html(0);
    $(this).val($(this).val().substring(0, 800));
  }
})
var articleImgList=[];
var typeId;
/*获取当前医生的id*/
var doctorId=sessionStorage.getItem('doctorId');
$(function(){
    $('.textCount').html(800-$('#ecchangeMessage,#ecchangeMessage1').val().length);
    /*发布帖子*/
    $('.reply-btn').click(function(){
    	 $('#my-modal-loading').modal('open');
    	if($('#ecchangeMessage,#ecchangeMessage1').val().length!==0){
    		var imgData=[];
        var imglist=$('#fileList').children();
        for (var i = 0; i < imglist.length; i++) {
            imgData.push(imglist[i].childNodes[0].src);
        }
        console.log(imglist)
        var articleText=$('#ecchangeMessage,#ecchangeMessage1').val();
        	 ym.ajax({
              url: "/communication/insertExchange",
              param:{
                  title:$('#article-title').val(),
                  ecchangeMessage:articleText
              },
              success: function (data) {
                 	if(JSON.parse(data).res=='1') {
                 		 uploadImgs(JSON.parse(data).obj,3);
                      if(imgList.length >0){
                    			uploadImgs(JSON.parse(data).obj,3);
                    		}else{
                    			$('#my-modal-loading').modal('close');
                    			$('#ceng #info-text').html('发表成功');
                    			$('#ceng').modal('open');
                    			 window.setTimeout(function(){
						                    	$('#ceng').modal('close');
						                    		window.location.href='taolunhuodong.html';
						                  },1000)
                    		}
                  }else{
                  	 $('#my-modal-loading').modal('close');
                  	$('#info-text').html('发表失败!');
                  	$('#ceng').modal('open');
                  	window.setTimeout(function(){
							        	$('#ceng').modal('close');
							      },800)
                  }
                  
              }
          });
    }else{
      $('#ceng').modal('open');
      $('#info-text').html('内容还未填写完善!');
      window.setTimeout(function(){
        $('#ceng').modal('close');
      },500)
    }
    })
    /*获取问医生菜单-----列表*/
    function getNavList(){
    		var navListHTML="";
        ym.ajax({
            url: "/DeclicateAskAnswer/selectParentMenu",
            param:{},
            success: function (data) {
               if (data.obj) {
                  var swiper = new Swiper('.swiper-container', {
                      slidesPerView: 2,
                      centeredSlides: false,
                      spaceBetween: 10,
                      pagination: {
                        el: '.swiper-pagination',
                        type: 'fraction',
                      },
                      // navigation: {
                      //   nextEl: '.swiper-button-next',
                      //   prevEl: '.swiper-button-prev',
                      // },
                      virtual: {
                        slides: (function () {
                          var slides = [];
                          for (var i = 0; i < data.obj.length; i ++) {
                            slides.push("<li curIndex='"+data.obj[i].delicateMenuId+"'>"+
                                          "<div>"+
                                              "<a href='#'>"+
                                                "<img src='../img/"+data.obj[i].delicateMenuIco+"' class='ask-doc-img' />"+
                                                "<h3 class='am-gallery-title'>"+data.obj[i].delicateMenuName+"</h3>"+
                                              "</a>"+
                                          "</div>"+
                                        "</li>");
                          }
                          return slides;
                        }()),
                      },
                    });
                  /*默认查询咨询类型1下的咨询问题关键字列表*/
                  typeId=data.obj[0].delicateMenuId;
                  ym.ajax({
                      url: "/DeclicateAskAnswer/selectThreeMenuByParentId",
                      param:{
                          ymDelicateParentId:data.obj[0].delicateMenuId,
                      },
                      success: function (data) {
                         if (data.obj) {
                            menuLists="";
                            for (var i = 0; i < data.obj.length; i++) {
                              menuLists+="<li menuIndex='"+data.obj[i].delicateMenuId+"'><a href='#'>"+data.obj[i].delicateMenuName+"</a></li>"
                            }
                            $('.menus').html(menuLists);
                          }
                      }
                  });
                }
            }
        });
    }
    getNavList();
    /*点击列表获取下方详细菜单*/
    window.setTimeout(function(){
        var menuLists="";
        /*选择咨询类型*/
        $('.ask-doc-topNav li').click(function(){
        		$(this).parent().addClass('swiper-slide-active').siblings().removeClass('swiper-slide-active');
            var curIndex=$(this).attr('curIndex');
            typeId=curIndex;
            ym.ajax({
                url: "/DeclicateAskAnswer/selectThreeMenuByParentId",
                param:{
                    ymDelicateParentId:curIndex,
                },
                success: function (data) {
                   if (data.obj) {
                      menuLists="";
                      for (var i = 0; i < data.obj.length; i++) {
                        menuLists+="<li menuIndex='"+data.obj[i].delicateMenuId+"'><a href='#'>"+data.obj[i].delicateMenuName+"</a></li>"
                      }
                      $('.menus').html(menuLists);
                    }
                }
            });
            
        })
        /*问医生发布帖子*/
      		$('.reply-btn1').click(function(){
      			console.log(imgList.length);
      			$('#my-modal-loading').modal('open');
                if($('#ecchangeMessage,#ecchangeMessage1').val().length!==0){
            		var imgData=[];
                var imglist=$('#fileList').children();
                for (var i = 0; i < imglist.length; i++) {
                    imgData.push(imglist[i].childNodes[0].src);
                }
                var articleText=$('#ecchangeMessage,#ecchangeMessage1').val();
                    ym.ajax({
                      url: "/Answer/insertYmAnswer",
                      param:{
                          ymAttachments:articleImgList,
                          answerDes:articleText,
                          typeId:doctorId,
                          type:2,
                          parentId:doctorId,
                          doctorId:doctorId
                      },
                      success: function (data) {
                      	if(data.res==1){
                        		if(imgList.length >0){
                        			console.log("sdf")
                        			uploadImgs(data.obj[0],2);
                        		}else{
                        			$('#my-modal-loading').modal('close');
                        			$('#ceng #info-text').html('发表成功，等待医生回复');
                        			$('#ceng').modal('open');
                        			 window.setTimeout(function(){
							                    	$('#ceng').modal('close');
							                    		window.location.href='askDoctor.html';
							                  },1000)
                        		}
                        }else{
                        	$('#my-modal-loading').modal('close');
                          	$('#info-text').html('发问失败!');
                          	$('#ceng').modal('open');
                          	window.setTimeout(function(){
                               $('#ceng').modal('close');
                               $('#info-text').html();
                             },1000)
                         }
                      }
                  });
                }else{
                  $('#ceng').modal('open');
                  $('#info-text').html('输入内容后再发布');
                  window.setTimeout(function(){
                    $('#ceng').modal('close');
                  },500)
                }
            })
        
    },1000)
    /*跳转到问题详情页面*/
         $('body').on('click','.menus>li',function(){
          var delicateMenuId = $(this).attr('menuIndex');
          console.log(delicateMenuId);
          window.location.href = "problemList.html?delicateMenuId="+delicateMenuId;
        })
    $('.whoes-pro').click(function(){
      window.location.href="problemFor.html";
    })
    // $('#ecchangeMessage1').focus(function(){
    //   $('.pro-tips').css('display','none')
    // })
    
    var delParent;
    var defaults = {
        fileType         : ["jpg","png","bmp","jpeg"],   // 上传文件的类型
        fileSize         : 1024 * 1024 * 10                  // 上传文件的大小 10M
    };
    var curTabImg;
        /*点击图片的文本框*/
    $(".file").change(function(){
        var idFile = $(this).attr("id");
        var file = document.getElementById(idFile);
        var imgContainer = $(this).parents(".z_photo"); //存放图片的父亲元素
        var fileList = file.files; //获取的图片文件
        var input = $(this).parent();//文本框的父亲元素
        var imgArr = [];
        //遍历得到的图片文件
        var numUp = imgContainer.find(".up-section").length;
        var totalNum = numUp + fileList.length;  //总的数量
        if(fileList.length > 9 || totalNum > 9 ){
            alert("上传图片数目不可以超过9个，请重新选择");  //一次选择上传超过5个 或者是已经上传和这次上传的到的总数也不可以超过5个
        }
        else if(numUp < 9){
            fileList = validateUp(fileList);
            for(var i = 0;i<fileList.length;i++){
             var imgUrl = window.URL.createObjectURL(fileList[i]);
                 imgArr.push(imgUrl);
                 imgList.push(fileList[i])
             var $section = $("<section class='up-section fl loading'>");
                 imgContainer.prepend($section);
             var $span = $("<span class='up-span'>");
                 $span.appendTo($section);
            
             var $img0 = $("<img class='close-upimg'>").on("click",function(event){
                    curTabImg=$(this).parent()[0].textContent;
                    event.preventDefault();
                    event.stopPropagation();
                    $(".works-mask").show();
                    delParent = $(this).parent();
                });   
                $img0.attr("src","../img/a7.jpg").appendTo($section);
             var $img = $("<img class='up-img up-opcity'>");
                 $img.attr("src",imgArr[i]);
                 $img.appendTo($section);
             var $p = $("<p class='img-name-p'>");
                 $p.html(fileList[i].name).appendTo($section);
             var $input = $("<input id='taglocation' name='taglocation' value='' type='hidden'>");
                 $input.appendTo($section);
             var $input2 = $("<input id='tags' name='tags' value='' type='hidden'/>");
                 $input2.appendTo($section);
              
           }
        }
        console.log(imgList)
        setTimeout(function(){
             $(".up-section").removeClass("loading");
             $(".up-img").removeClass("up-opcity");
         },450);
         numUp = imgContainer.find(".up-section").length;
        if(numUp >= 9){
            $(this).parent().hide();
        }
        
        //input内容清空
        $(this).val("");
    });
    
    
   
    $(".z_photo").delegate(".close-upimg","click",function(){
          $(".works-mask").show();
          delParent = $(this).parent();
          console.log('adsd')
    });
        
    $(".wsdel-ok").click(function(){
        $(".works-mask").hide();
        for (var i = 0; i < imgList.length; i++) {
          if(imgList[i].name==curTabImg){
                 imgList.splice((i-1),1);
                 console.log(imgList)
          }
         }
        var numUp = delParent.siblings().length;
        if(numUp < 10){
            delParent.parent().find(".z_file").show();
        }
         delParent.remove();
        
    });
    
    $(".wsdel-no").click(function(){
        $(".works-mask").hide();
    });
        
        function validateUp(files){
            var arrFiles = [];//替换的文件数组
            for(var i = 0, file; file = files[i]; i++){
                //获取文件上传的后缀名
                var newStr = file.name.split("").reverse().join("");
                if(newStr.split(".")[0] != null){
                        var type = newStr.split(".")[0].split("").reverse().join("");
                        console.log(type+"===type===");
                        if(jQuery.inArray(type, defaults.fileType) > -1){
                            // 类型符合，可以上传
                            if (file.size >= defaults.fileSize) {
                                $('#ceng').modal('open');
                                $('#info-text').html('您这个"'+ file.name +'"文件大小过大');
                                window.setTimeout(function(){
                                  $('#ceng').modal('close');
                                },800)  
                            } else {
                                // 在这里需要判断当前所有文件中
                                arrFiles.push(file);    
                            }
                        }else{
                            $('#ceng').modal('open');
                            $('#info-text').html('您这个"'+ file.name +'"上传类型不符合');
                                window.setTimeout(function(){
                                  $('#ceng').modal('close');
                            },800) 
                        }
                    }else{
                        alert(); 
                        $('#ceng').modal('open');
                        $('#info-text').html('您这个"'+ file.name +'"没有类型, 无法识别');
                                window.setTimeout(function(){
                                  $('#ceng').modal('close');
                        },800)    
                    }
            }
            return arrFiles;
        }
    
    
    
    
    
    
})

/*上传图片*/
function uploadImgs(id,relevanceTpyeId){
    var formData=new FormData();
    for(var i=0;i<imgList.length;i++){
        if(i==0){
            formData.append("imageFile",imgList[0]);
            formData.append("relevanceTpyeDetail",0);
        }else{
            formData.append("imageFile"+(i+1)+"",imgList[i]);
            formData.append("relevanceTpyeDetail"+(i+1)+"",0);
        }
    }
    formData.append("relevanceId",id);
    formData.append("relevanceTpyeId",relevanceTpyeId);
    $.ajax({
        url: ym.url+"/uploadVideoAndImage",
        type : "post",
        processData: false,
        contentType: false,
        data: formData,
        success : function(data) {
        	console.log(data.res);
        	if(data.res == 1){
        		$('#my-modal-loading').modal('close');
              		$('#ceng').modal('open');
              		var zhi = $('#ceng #info-text').html();
                    window.setTimeout(function(){
	                    $('#ceng').modal('close');
	                    	if(zhi == "发表成功"){
	                    		window.location.href='taolunhuodong.html';
	                    	}else{
	                    		window.location.href='askDoctor.html';
	                    	}
	                 },800)
	                  
        	}else{
        		$('#my-modal-loading').modal('close');
        		$('#ceng2').modal('open');
             var zhi =$('#ceng2').text().trim(); 
             console.log(zhi);
             if(zhi == "发问失败"){
	             	ym.ajax({
		              url: "/Answer/deleteYmAnswer",
		              param:{
		                  answerId:id
		              },
		              success: function (data) {
		              	$('#ceng2').modal('close');
		              	if(data.res==1){
		              		setTimeout(function(){
			             			$('#ceng2').modal('close');
			             				window.location.href="askDoctor.html";
			             		},800)
		              	}
		              }
		          });
             }else{
        				$('#ceng2').modal('open');
             		setTimeout(function(){
             			$('#ceng2').modal('close');
             				window.location.href="taolunhuodong.html"
             		},800)
             }
        		
        		
        		
        		
        		/*setTimeout(function(){
        			$('#ceng').modal('open');
        			window.setTimeout(function(){
        			var zhi = $('#ceng #info-text').html();	
                    $('#ceng').modal('close');
                    	if(zhi == "发表成功"){
                    		window.location.href='taolunhuodong.html';
                    	}else{
                    		window.location.href='askDoctor.html';
                    	}
                   },800)
        		})*/
        	}
            
         },
        error: function (data) {
            console.log(data);
        }
    });
}
